package com.example.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.crm.entity.CustomerTag;
import com.example.crm.entity.CustomerTagRelation;
import com.example.crm.mapper.CustomerTagMapper;
import com.example.crm.mapper.CustomerTagRelationMapper;
import com.example.crm.service.CustomerTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 客户标签服务实现类
 */
@Service
public class CustomerTagServiceImpl extends ServiceImpl<CustomerTagMapper, CustomerTag> implements CustomerTagService {

    @Autowired
    private CustomerTagRelationMapper tagRelationMapper;

    @Override
    public List<CustomerTag> listAllTags() {
        LambdaQueryWrapper<CustomerTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerTag::getDeleted, 0);
        queryWrapper.orderByAsc(CustomerTag::getName);
        return list(queryWrapper);
    }

    @Override
    public List<CustomerTag> getTagsByCustomerId(Long customerId) {
        return baseMapper.selectTagsByCustomerId(customerId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setCustomerTags(Long customerId, List<Long> tagIds) {
        // 先删除客户原有标签关联
        tagRelationMapper.deleteByCustomerId(customerId);
        
        // 如果没有新标签，则直接返回成功
        if (tagIds == null || tagIds.isEmpty()) {
            return true;
        }
        
        // 添加新标签关联
        List<CustomerTagRelation> relations = new ArrayList<>();
        for (Long tagId : tagIds) {
            CustomerTagRelation relation = new CustomerTagRelation();
            relation.setCustomerId(customerId);
            relation.setTagId(tagId);
            relations.add(relation);
        }
        
        // 批量插入关联记录
        for (CustomerTagRelation relation : relations) {
            tagRelationMapper.insert(relation);
        }
        
        return true;
    }
} 